package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.bson.Document;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sentiment.bean.OperationInfo;
import com.sentiment.database.bean.Keyword;
import com.sentiment.database.bean.UserInfo;
import com.sentiment.database.bean.WebsiteInfo;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.dbutil.UtilDao;
import com.sentiment.shiro.ActiveUser;
import com.sentiment.tools.Format;

/**
 * Servlet implementation class UserWebsiteServlet
 */
@WebServlet("/UserWebsiteServlet")
public class UserWebsiteServlet extends HttpServlet {
	private static final long serialVersionUID = 5464641L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserWebsiteServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String methodName = request.getParameter("method");
		try {
			Method method = getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	/**
	 * 查看用户所有关注的网页
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getWebsite(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		
		String jsonStr = "";
		String user_id = "";
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		if(activeUser == null){
			jsonStr = "{\"Info\":"+ "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
			user_id = activeUser.getUser_id();
			long count = 0;
			UserInfo userinfo = new UserInfo();
			userinfo = userinfo.getUserInfoByUser_id(user_id);
			if(userinfo == null){
				jsonStr = "{\"recordsTotal\":"+ count +",\"Info\":" + "\"" + OperationInfo.NoKeywords + "\"" +"}";
			}else{
				List<String> websiteidList = userinfo.getWebsiteList();		
				if(websiteidList != null && websiteidList.size() != 0){
					count = websiteidList.size();
					List<WebsiteInfo> websiteinfolist = new ArrayList<>();
					DbUtil db = new DbUtil();
					db.openConnection(WebsiteInfo.dbName,WebsiteInfo.collection);
					for (int i = 0; i < count; i++) {
					    Document t = db.query(websiteidList.get(i));
						WebsiteInfo websiteinfo = new WebsiteInfo(t);
						websiteinfolist.add(websiteinfo);
					}
					db.closeConnection();
					ObjectMapper mapper = new ObjectMapper();
					String jsonArr = "";
					try {
						jsonArr = mapper.writeValueAsString(websiteinfolist);
					} catch (JsonProcessingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					jsonStr = "{\"recordsTotal\":"+ count +",\"websites\":" + jsonArr+"}";
				}else{
					jsonStr = "{\"recordsTotal\":"+ count +",\"Info\":" + "\"" + OperationInfo.NoKeywords + "\"" +"}";
				}
			}
		}
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
	/**
	 * 用户添加一个关注的网页
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void addWebsite(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		
		String websiteStr = request.getParameter("website");
		
		String jsonStr = "";
		String user_id = "";
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		if(activeUser == null){
			jsonStr = "{\"Info\":"+ "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
			user_id = activeUser.getUser_id();
			//删除 WebsiteInfo 表中数据
			DbUtil db = new DbUtil();
			db.openConnection(WebsiteInfo.dbName, WebsiteInfo.collection);
			WebsiteInfo websiteinfo = new WebsiteInfo(websiteStr, Format.date2String(new Date(), 3));
			String website_id = db.insertGetId(websiteinfo.toDocument()).toString();
			db.closeConnection();
			
			//删除  UserInfo 表中数据				
			UserInfo userinfo = new UserInfo();
			userinfo = userinfo.getUserInfoByUser_id(user_id);
			boolean userinfoflag = true;
			if(userinfo == null){
				userinfoflag = false;
			}else{
				List<String> websiteList = userinfo.getWebsiteList();			
				if(websiteList == null)
					websiteList = new ArrayList<>();
				websiteList.add(website_id);
				userinfo.setWebsiteList(websiteList);
				db.openConnection(UserInfo.dbName, UserInfo.collection);
				userinfoflag = db.update(userinfo.toDocument(), new String[]{"user_id"}, userinfo.toDocument(), new String[]{"websiteList"});
				db.closeConnection();
			}
			
			if(userinfoflag){
				jsonStr = "{\"info\":"+ "\"" + OperationInfo.OperSuccess + "\"" +"}"; 
			}else{
				jsonStr = "{\"info\":"+ "\"" + OperationInfo.OperFailure + "\"" +"}"; 
			}
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}
	
	/**
	 * 用户删除一个关注的网页
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void removeWebsites(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		
		String website_id = request.getParameter("website_id");
		
		String jsonStr = "";
		String user_id = "";
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		if(activeUser == null){
			jsonStr = "{\"Info\":"+ "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
			user_id = activeUser.getUser_id();
			//删除 WebsiteInfo 表中数据
			DbUtil db = new DbUtil();
			db.openConnection(WebsiteInfo.dbName, WebsiteInfo.collection);
			WebsiteInfo websiteinfo = new WebsiteInfo();
			websiteinfo.set_id(website_id);
			boolean websiteflag = db.remove(websiteinfo.toDocument_id(), new String[]{"_id"});
			db.closeConnection();
			
			//删除  UserInfo 表中数据				
			UserInfo userinfo = new UserInfo();
			userinfo = userinfo.getUserInfoByUser_id(user_id);
			boolean userinfoflag = true;
			if(userinfo == null){
				userinfoflag = false;
			}else{
				List<String> websiteList = userinfo.getWebsiteList();			
				if(websiteList.contains(website_id)){
					websiteList.remove(website_id);
					userinfo.setWebsiteList(websiteList);
					db.openConnection(UserInfo.dbName, UserInfo.collection);
					userinfoflag = db.update(userinfo.toDocument(), new String[]{"user_id"}, userinfo.toDocument(), new String[]{"websiteList"});
					db.closeConnection();
				}
			}
			
			if(websiteflag && userinfoflag){
				jsonStr = "{\"info\":"+ "\"" + OperationInfo.OperSuccess + "\"" +"}"; 
			}else{
				jsonStr = "{\"info\":"+ "\"" + OperationInfo.OperFailure + "\"" +"}"; 
			}
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}

}
